﻿using Hyjx.FeedingService.Objects;
using Hyjx.GanFengLogger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;

namespace Hyjx.FeedingService
{
    /// <summary>
    /// 应用 Http 功能
    /// </summary>
    internal class AppHttp
    {
        readonly ILogger<Feeding> _logger;
        readonly JsonSerializerOptions _jsonSerializerOptions;

        public AppHttp(ILogger<Feeding> logger)
        {
            _logger = logger;
            _jsonSerializerOptions = new JsonSerializerOptions() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };

        }

        /// <summary>
        /// 发送搅拌机（稀释）状态改变
        /// </summary>
        /// <param name="url">基本地址</param>
        /// <param name="args">稀释搅拌机状态参数</param>
        internal void SendDilutionStatusChanged(string url, ReportStatusArgs args) => HttpPostAsync(url, args.DeviceCode, 225, args);

        /// <summary>
        /// 发送搅拌机（稀释）实时状态
        /// </summary>
        /// <param name="url">基本地址</param>
        /// <param name="args">搅拌机状态参数</param>
        internal void SendDilutionStatus(string url, ReportStatusArgs args) => HttpPostAsync(url, args.DeviceCode, 227, args);

        /// <summary>
        /// 发送搅拌机（制胶）状态改变
        /// </summary>
        /// <param name="url">基本地址</param>
        /// <param name="args">稀释搅拌机状态参数</param>
        internal void SendGlueStatusChanged(string url, ReportMixerStatusArgs args) => HttpPostAsync(url, args.DeviceCode, 205, args);

        /// <summary>
        /// 发送搅拌机（制胶）实时状态
        /// </summary>
        /// <param name="url">基本地址</param>
        /// <param name="args">搅拌机状态参数</param>
        internal void SendGlueStatus(string url, ReportMixerStatusArgs args) => HttpPostAsync(url, args.DeviceCode, 207, args);

        async void HttpPostAsync(string url, string deviceCode, int interfaceId, object args)
        {
            using HttpClient http = new();
            HttpResponseMessage response;
            LogObject log = new()
            {
                DeviceCode = deviceCode,
                InterfaceId = interfaceId,
                RequestUrl = url,
                RequestContent = JsonSerializer.Serialize(args, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs, UnicodeRanges.CjkUnifiedIdeographsExtensionA)
                })
            };

            try
            {
                response = await http.PostAsJsonAsync(url, args); // 提交
                log.ResponseContent = JsonSerializer.Serialize(response);

                if (response.StatusCode == System.Net.HttpStatusCode.NotFound || response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                    logger.Append("找不到 MES 接口或访问受限。");
                    logger.CompleteWithWarning();
                }
                else
                {
                    GanFengResult? result = response.Content.ReadFromJsonAsync<GanFengResult>().GetAwaiter().GetResult();
                    if (result == null)
                    {
                        GFLogger lg = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                        lg.Append("访问失败");
                        lg.CompleteWithWarning($"响应结果无法反序列化");
                    }
                    else if (result.Code != 0)
                    {
                        GFLogger lg = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                        lg.Append("访问失败");
                        lg.CompleteWithWarning($"响应代码：{result.Code}；信息：{result.Message}");
                    }
                    else
                    {
                        GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                        logger.Append("访问成功");
                        logger.CompleteWithInformation();
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                logger.Append("MES 访问失败，可能网络已经断开。");
                logger.CompleteWithError(ex);
            }
            catch (Exception ex)
            {
                GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                logger.Append("MES 访问出现错误。");
                logger.CompleteWithError(ex);
            }
        }
    }
}
